package com.fastjars.business.shiro.filter;

import com.fastjars.business.shiro.session.SessionManager;
import com.fastjars.business.shiro.session.SessionStatus;
import com.fastjars.business.spring.http.Resp;
import org.apache.commons.util.RequestUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * ManagerKickOutUserFilter
 * 管理员强制踢出用户
 *
 * @author Brant Liu <br>
 * 邮箱：lbf1988@qq.com <br>
 * 日期：2018/5/9
 * @version 1.0.0
 */
public class ManagerKickOutUserFilter extends LogoutFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = this.getSubject(request, response);
        Session session = subject.getSession();
        SessionStatus sessionStatus = (SessionStatus) session.getAttribute(SessionManager.DEFAULT_SESSION_STATUS);
        // TODO: 2017/09/22 判断用户是否被锁定和强制退出
        if (null != sessionStatus && (sessionStatus.getOnlineStatus() == SessionStatus.SESSION_STATUS_LOGOUT || sessionStatus.getOnlineStatus() == SessionStatus.SESSION_STATUS_LOCK)) {
            try {
                subject.logout();
            } catch (SessionException var6) {
            }
            // TODO: 2018/5/9 Ajax请求处理
            WebUtils.saveRequest(request);
            if (RequestUtils.isAjaxRequest((HttpServletRequest) request)) {
                WriterUtils.write(response, Resp.kickOutLogin().build().toJsonString());
                return false;
            }
            super.issueRedirect(request, response, super.getRedirectUrl());
            return false;
        }
        return true;
    }
}
